import Api2d from 'api2d'
import { OpenAi } from '@/utils'
import useGlobalSetting from '@/hooks/useGlobalSetting'
import axios from 'axios'

const { openProxy, openModel, openKey, openMaxTokens } = useGlobalSetting()
const timeout = 1000 * 60 // 60s

export const generateText = async (messages: ChatMessage[]) => {
  const apiUrl = openProxy.value
  const apiKey = openKey.value

  // 使用 AbortController 实现超时取消
  const controller = new AbortController()
  const timer = setTimeout(() => {
    controller.abort()
  }, timeout)

  try {
    const response = await axios.post(apiUrl, {
      model: openModel.value,
      messages,
      stream: false,
      max_tokens: +openMaxTokens.value,
    }, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      signal: controller.signal
    })

    return response.data
  } catch (error) {
    console.error('请求出错：', error)
    throw error
  } finally {
    clearTimeout(timer)
  }
}


// 获取openapi余额接口已失效
// export const generateDashboardInfo = async (apiKey: string, proxy?: string) => {
//   const openai = new OpenAi(apiKey, proxy)

//   const { url, initOptions } = openai.generateDashboardPayload()
//   try {
//     const response = await fetch(url, initOptions)
//     const data = await response.json()
//     return data
//   }
//   catch (error) {
//     return `[Error] ${(error as any).message}. try again later or try using proxy`
//   }
// }

export const generatTranslate = async (text: string) => {
  const apiUrl = openProxy.value
  const apiKey = openKey.value

  // 使用 AbortController 实现超时控制
  const controller = new AbortController()
  const timer = setTimeout(() => {
    controller.abort()
  }, timeout)

  const system ='You are a translation engine that can only translate text and cannot interpret it, ensuring that the translation is clear, concise, and coherent.'
  const assistantPrompt = `Please translate the following text into Chinese Simplified: ${text}`

  try {
    const response = await axios.post(
      apiUrl,
      {
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: system },
          { role: 'user', content: assistantPrompt }
        ],
        temperature: 1,
        n: 1,
        stream: false
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        signal: controller.signal
      }
    )
    console.log(response.data)
    return response.data
  } catch (error) {
    console.error('请求出错：', error)
    throw error
  } finally {
    clearTimeout(timer)
  }
}


export const generatAnalysis = async (text: string) => {
  const apiUrl = openProxy.value
  const apiKey = openKey.value

  // 利用 AbortController 设置超时
  const controller = new AbortController()
  const timer = setTimeout(() => {
    controller.abort()
  }, timeout)

  const system =
    '我想让gpt扮演我的语法老师，不论我说什么语言你都需要用中文纠正我语法的错误，如果语法没有错误，则回复\'无语法错误\''
  const assistantPrompt = `'${text}'`

  try {
    const response = await axios.post(
      apiUrl,
      {
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: system },
          { role: 'user', content: assistantPrompt }
        ],
        temperature: 1,
        n: 1,
        stream: false,
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        signal: controller.signal,
      }
    )
    console.log(response.data)
    return response.data
  } catch (error) {
    console.error('请求出错：', error)
    throw error
  } finally {
    clearTimeout(timer)
  }
}
